package utils

import (
	"crypto/tls"
	"fmt"
	"net/mail"
	"net/smtp"
	"regexp"

	log "github.com/zeromicro/go-zero/core/logx"
)

// 发送邮件的函数
func SendEmail(user, password, host, to, subject, body, contentType string) error {
	// 构建邮件内容
	header := make(map[string]string)
	header["From"] = user
	header["To"] = to
	header["Subject"] = subject
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = fmt.Sprintf("%s; charset=UTF-8", contentType)

	message := ""
	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + body

	// 定义SMTP服务器地址和端口
	auth := smtp.PlainAuth("", user, password, host)

	// 创建TLS配置
	tlsConfig := &tls.Config{
		InsecureSkipVerify: false,
		ServerName:         host,
	}

	// 连接到SMTP服务器
	conn, err := tls.Dial("tcp", host+":465", tlsConfig)
	if err != nil {
		log.Error(err)
		return err
	}
	defer conn.Close()

	// 创建SMTP客户端
	c, err := smtp.NewClient(conn, host)
	if err != nil {
		log.Error(err)
		return err
	}
	defer c.Quit()

	// 设置身份验证信息
	err = c.Auth(auth)
	if err != nil {
		log.Error(err)
		return err
	}

	// 设置邮件发送者和接收者
	t, err := mail.ParseAddress(to)
	if err != nil {
		log.Error(err)
		return err
	}

	f, err := mail.ParseAddress(user)
	if err != nil {
		log.Error(err)
		return err
	}

	err = c.Mail(f.Address)
	if err != nil {
		log.Error(err)
		return err
	}

	err = c.Rcpt(t.Address)
	if err != nil {
		log.Error(err)
		return err
	}

	// 创建邮件写入器
	w, err := c.Data()
	if err != nil {
		log.Error(err)
		return err
	}

	// 写入邮件内容
	_, err = w.Write([]byte(message))
	if err != nil {
		log.Error(err)
		return err
	}

	// 关闭邮件写入器
	err = w.Close()
	if err != nil {
		log.Error(err)
		return err
	}

	fmt.Println("邮件发送成功！")
	return nil
}

func CheckSignedOffBy(message string) bool {
	// match "Signed-off-by"
	re := regexp.MustCompile(`Signed-off-by:\s+\S+\s+<\S+@\S+\.\S+>`)
	return re.MatchString(message)
}

func GetSignedOffBy(message string) (string, string, error) {
	// match "Signed-off-by" name and email
	re := regexp.MustCompile(`Signed-off-by:\s+(\S+)\s+<(\S+@\S+\.\S+)>`)

	// match
	matches := re.FindStringSubmatch(message)
	if matches == nil {
		return "", "", fmt.Errorf("no 'Signed-off-by' signature found")
	}

	//get name and email
	name := matches[1]
	email := matches[2]

	return name, email, nil
}
